const { Tenant, User } = require('../models');
const { nanoid } = require('nanoid');

class TenantService {
  // 创建新租户
  async createTenant(tenantData) {
    const { name, domain, email, adminUser } = tenantData;
    
    try {
      // 检查域名是否已存在
      const existingTenant = await Tenant.findByDomain(domain);
      if (existingTenant) {
        throw new Error('Domain already exists');
      }
      
      // 验证域名格式
      if (!/^[a-z0-9-]+$/.test(domain)) {
        throw new Error('Invalid domain format. Only lowercase letters, numbers, and hyphens are allowed');
      }
      
      // 创建租户
      const tenant = new Tenant({
        name,
        domain: domain.toLowerCase(),
        email: email.toLowerCase(),
        status: 'active' // 可以设置为 'pending' 需要审核
      });
      
      await tenant.save();
      
      // 如果提供了管理员用户信息，创建管理员用户
      let adminUserResult = null;
      if (adminUser) {
        const { User } = require('../models');
        
        const admin = new User({
          tenantId: tenant.tenantId,
          email: adminUser.email.toLowerCase(),
          password: adminUser.password,
          firstName: adminUser.firstName,
          lastName: adminUser.lastName,
          role: 'admin',
          status: 'active'
        });
        
        // 自动验证管理员邮箱
        admin.security.emailVerified = true;
        
        await admin.save();
        
        adminUserResult = {
          id: admin._id,
          email: admin.email,
          fullName: admin.fullName,
          role: admin.role
        };
      }
      
      return {
        tenant: {
          id: tenant._id,
          tenantId: tenant.tenantId,
          name: tenant.name,
          domain: tenant.domain,
          email: tenant.email,
          status: tenant.status,
          plan: tenant.plan,
          settings: tenant.settings
        },
        adminUser: adminUserResult,
        message: 'Tenant created successfully'
      };
      
    } catch (error) {
      throw new Error(`Failed to create tenant: ${error.message}`);
    }
  }
  
  // 获取租户列表
  async getTenants(options = {}) {
    try {
      const {
        page = 1,
        limit = 20,
        status,
        plan,
        search,
        sortBy = 'createdAt',
        sortOrder = 'desc'
      } = options;
      
      const query = {};
      
      // 状态过滤
      if (status) {
        query.status = status;
      }
      
      // 计划过滤
      if (plan) {
        query.plan = plan;
      }
      
      // 搜索过滤
      if (search) {
        query.$or = [
          { name: { $regex: search, $options: 'i' } },
          { domain: { $regex: search, $options: 'i' } },
          { email: { $regex: search, $options: 'i' } }
        ];
      }
      
      const skip = (page - 1) * limit;
      const sort = { [sortBy]: sortOrder === 'desc' ? -1 : 1 };
      
      const [tenants, total] = await Promise.all([
        Tenant.find(query)
          .sort(sort)
          .skip(skip)
          .limit(limit)
          .lean(),
        Tenant.countDocuments(query)
      ]);
      
      return {
        tenants,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      };
      
    } catch (error) {
      throw new Error(`Failed to get tenants: ${error.message}`);
    }
  }
  
  // 根据ID获取租户详情
  async getTenantById(tenantId) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      // 获取租户统计信息
      const stats = await this.getTenantStats(tenantId);
      
      return {
        tenant: {
          id: tenant._id,
          tenantId: tenant.tenantId,
          name: tenant.name,
          domain: tenant.domain,
          email: tenant.email,
          status: tenant.status,
          plan: tenant.plan,
          settings: tenant.settings,
          subscription: tenant.subscription,
          createdAt: tenant.createdAt,
          updatedAt: tenant.updatedAt,
          isActive: tenant.isActive,
          isSubscriptionExpired: tenant.isSubscriptionExpired,
          daysRemaining: tenant.daysRemaining
        },
        stats
      };
      
    } catch (error) {
      throw new Error(`Failed to get tenant: ${error.message}`);
    }
  }
  
  // 更新租户信息
  async updateTenant(tenantId, updateData) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      // 检查域名是否被其他租户使用
      if (updateData.domain && updateData.domain !== tenant.domain) {
        const existingTenant = await Tenant.findByDomain(updateData.domain);
        if (existingTenant) {
          throw new Error('Domain already exists');
        }
      }
      
      // 更新允许的字段
      const allowedFields = ['name', 'domain', 'email', 'status', 'plan'];
      const updates = {};
      
      allowedFields.forEach(field => {
        if (updateData[field] !== undefined) {
          updates[field] = updateData[field];
        }
      });
      
      Object.assign(tenant, updates);
      await tenant.save();
      
      return {
        tenant: {
          id: tenant._id,
          tenantId: tenant.tenantId,
          name: tenant.name,
          domain: tenant.domain,
          email: tenant.email,
          status: tenant.status,
          plan: tenant.plan,
          updatedAt: tenant.updatedAt
        },
        message: 'Tenant updated successfully'
      };
      
    } catch (error) {
      throw new Error(`Failed to update tenant: ${error.message}`);
    }
  }
  
  // 更新租户设置
  async updateTenantSettings(tenantId, settings) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      await tenant.updateSettings(settings);
      
      return {
        settings: tenant.settings,
        message: 'Tenant settings updated successfully'
      };
      
    } catch (error) {
      throw new Error(`Failed to update tenant settings: ${error.message}`);
    }
  }
  
  // 删除租户
  async deleteTenant(tenantId) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      // 检查是否有活跃用户
      const userCount = await User.countDocuments({ tenantId });
      if (userCount > 0) {
        throw new Error('Cannot delete tenant with existing users. Please remove all users first.');
      }
      
      await tenant.deleteOne();
      
      return {
        message: 'Tenant deleted successfully'
      };
      
    } catch (error) {
      throw new Error(`Failed to delete tenant: ${error.message}`);
    }
  }
  
  // 激活租户
  async activateTenant(tenantId) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      await tenant.activate();
      
      return {
        message: 'Tenant activated successfully',
        tenant: {
          id: tenant._id,
          tenantId: tenant.tenantId,
          status: tenant.status
        }
      };
      
    } catch (error) {
      throw new Error(`Failed to activate tenant: ${error.message}`);
    }
  }
  
  // 停用租户
  async deactivateTenant(tenantId) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      await tenant.deactivate();
      
      return {
        message: 'Tenant deactivated successfully',
        tenant: {
          id: tenant._id,
          tenantId: tenant.tenantId,
          status: tenant.status
        }
      };
      
    } catch (error) {
      throw new Error(`Failed to deactivate tenant: ${error.message}`);
    }
  }
  
  // 暂停租户
  async suspendTenant(tenantId, reason = '') {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      await tenant.suspend();
      
      // 记录暂停原因
      if (reason) {
        tenant.metadata.set('suspensionReason', reason);
        tenant.metadata.set('suspensionDate', new Date());
        await tenant.save();
      }
      
      return {
        message: 'Tenant suspended successfully',
        tenant: {
          id: tenant._id,
          tenantId: tenant.tenantId,
          status: tenant.status
        }
      };
      
    } catch (error) {
      throw new Error(`Failed to suspend tenant: ${error.message}`);
    }
  }
  
  // 获取租户统计信息
  async getTenantStats(tenantId) {
    try {
      const [userCount, adminCount, activeUserCount] = await Promise.all([
        User.countDocuments({ tenantId }),
        User.countDocuments({ tenantId, role: 'admin' }),
        User.countDocuments({ tenantId, status: 'active' })
      ]);
      
      // 获取最近登录的用户
      const recentLogins = await User.find({ tenantId })
        .sort({ 'security.lastLogin': -1 })
        .limit(5)
        .select('email firstName lastName security.lastLogin')
        .lean();
      
      return {
        users: {
          total: userCount,
          active: activeUserCount,
          admins: adminCount
        },
        recentLogins: recentLogins.map(user => ({
          email: user.email,
          name: `${user.firstName} ${user.lastName}`,
          lastLogin: user.security.lastLogin
        }))
      };
      
    } catch (error) {
      throw new Error(`Failed to get tenant stats: ${error.message}`);
    }
  }
  
  // 更新租户订阅
  async updateSubscription(tenantId, subscriptionData) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      await tenant.updateSubscription(subscriptionData);
      
      return {
        subscription: tenant.subscription,
        message: 'Subscription updated successfully'
      };
      
    } catch (error) {
      throw new Error(`Failed to update subscription: ${error.message}`);
    }
  }
  
  // 检查域名可用性
  async checkDomainAvailability(domain) {
    try {
      const normalizedDomain = domain.toLowerCase();
      
      // 验证域名格式
      if (!/^[a-z0-9-]+$/.test(normalizedDomain)) {
        return {
          available: false,
          reason: 'Invalid domain format'
        };
      }
      
      // 检查长度
      if (normalizedDomain.length < 3 || normalizedDomain.length > 63) {
        return {
          available: false,
          reason: 'Domain must be between 3 and 63 characters'
        };
      }
      
      // 检查是否已存在
      const existingTenant = await Tenant.findByDomain(normalizedDomain);
      
      return {
        available: !existingTenant,
        domain: normalizedDomain,
        reason: existingTenant ? 'Domain already taken' : null
      };
      
    } catch (error) {
      throw new Error(`Failed to check domain availability: ${error.message}`);
    }
  }
  
  // 获取租户功能使用情况
  async getFeatureUsage(tenantId) {
    try {
      const tenant = await Tenant.findByTenantId(tenantId);
      if (!tenant) {
        throw new Error('Tenant not found');
      }
      
      const stats = await this.getTenantStats(tenantId);
      const limits = tenant.settings.limits;
      
      return {
        usage: {
          users: {
            current: stats.users.total,
            limit: limits.users,
            percentage: Math.round((stats.users.total / limits.users) * 100)
          },
          storage: {
            current: 0, // 需要实现存储使用量计算
            limit: limits.storage,
            percentage: 0
          },
          apiCalls: {
            current: 0, // 需要实现 API 调用计数
            limit: limits.apiCalls,
            percentage: 0
          }
        },
        features: Object.fromEntries(tenant.settings.features),
        plan: tenant.plan
      };
      
    } catch (error) {
      throw new Error(`Failed to get feature usage: ${error.message}`);
    }
  }
}

module.exports = new TenantService();